<template>
  <div>
    <form
      method="post"
      action="http://upload-z1.qiniup.com"
      enctype="multipart/form-data"
    >
      <input name="key" type="hidden" value="rename.jpg" />
      <input
        name="token"
        type="hidden"
        value="di0QoZTUFcBPUenjPF2jco9ewZR6nEHkR8kom_xv:_TDJkCf7Tm3xM3qStxiIRpLm60k=:eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsImNhbGxiYWNrQm9keSI6IntcImtleVwiOlwiJChrZXkpXCIsXCJoYXNoXCI6XCIkKGV0YWcpXCIsXCJmc2l6ZVwiOiQoZnNpemUpLFwiYnVja2V0XCI6XCIkKGJ1Y2tldClcIixcIm5hbWVcIjpcIiQoeDpuYW1lKVwifSIsInNjb3BlIjoidGVzdC1qaWFubXUiLCJkZWFkbGluZSI6MTcwNjM3OTIyMX0="
      />
      <input name="file" type="file" />
      <input type="submit" value="上传文件" />
    </form>
    <hr />
    <h2>方式二：API方式上传文件</h2>
    请选择你要上传的文件：<input type="file" id="file" />
  </div>
</template>

<script>
import { defineComponent, onMounted } from 'vue';
import * as qiniu from 'qiniu-js';
export default defineComponent({
  name: '',
  setup() {
    onMounted(() => {
      const file = document.getElementById('file');
      let fileData;
      file.addEventListener('change', () => {
        const observer = {
          next(res) {
            console.log(res);
          },
          error(err) {
            console.log(err);
          },
          complete(res) {
            console.log(res);
          },
        };
        fileData = file.files[0];
        // const formData = new FormData();
        // for (var i = 0; i < file.files.length; i++) {
        //   formData.append('upfile[]', file.files[i]);
        // }
        console.log('file', fileData);
        const token =
          'di0QoZTUFcBPUenjPF2jco9ewZR6nEHkR8kom_xv:PkJ1woMynjxAoRutMrNLzLc81kc=:eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsImNhbGxiYWNrQm9keSI6IntcImtleVwiOlwiJChrZXkpXCIsXCJoYXNoXCI6XCIkKGV0YWcpXCIsXCJmc2l6ZVwiOiQoZnNpemUpLFwiYnVja2V0XCI6XCIkKGJ1Y2tldClcIixcIm5hbWVcIjpcIiQoeDpuYW1lKVwiLFwiZXh0cmFjdFwiOlwiJCh4OnRlc3QpXCJ9Iiwic2NvcGUiOiJ0ZXN0LWppYW5tdSIsImRlYWRsaW5lIjoxNzA2NDI4Nzc2fQ==';
        const config = {
          useCdnDomain: true,
          region: qiniu.region.z1,
          fname: 'less.png',
        };
        const putExtra = {
          fname: 'shop.png',
          // mimeType: 'text/plain',
          customVars: { 'x:test': 'qiniu' },
          // metadata: { 'x-qn-meta': 'qiniu' },
        };
        const observable = qiniu.upload(
          fileData,
          'test.png',
          token,
          putExtra,
          config
        );
        const subscription = observable.subscribe(observer); // 上传开始
        // subscription.unsubscribe(); // 上传取消
        console.log(fileData);
        qiniu.getUploadUrl(config, token).then(res => {
          console.log('downAddress', res);
        });
      });
    });
    const upload = e => {
      console.log(e);
    };
    return {
      upload,
    };
  },
});
</script>

<style scoped></style>
